package com.zh.simple.web;

import com.zh.simple.App;
import com.zh.simple.common.ApiResult;
import com.zh.simple.support.SpringContextHolder;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

import static com.zh.mycommon.util.MyFileUtil.DATA_MB;
import static com.zh.simple.common.ApiResult.success;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @author Zhou
 * @date 0:02 2025/1/11
 */
@Slf4j
@RestController
public class HelloController {

    /**
     * 项目的路径
     */
    @GetMapping("/")
    public ApiResult<Map> hello1() throws IOException {
        log.info(">>> call hello1...");

        //获取项目路径
        String projectPath = System.getProperty("user.dir");
        log.info("project dir：{}", projectPath);

        //获取src路径
        File file = ResourceUtils.getFile("classpath:");
        var srcPath = file.getPath();

        return success(Map.of("project dir", projectPath, "src path", srcPath));
    }

    /**
     * 获取变量值
     *
     * @param key
     * @return
     */
    @GetMapping("/env")
    public ApiResult<Map> getProperty(@RequestParam(value = "key", defaultValue = "args") String key) {
        log.info(">>> call getProperty...");
        if ("args".equals(key.trim())) {
            return success(Map.of("args", Arrays.toString(App.getAppArgs())));
        }
        var property = Optional.ofNullable(SpringContextHolder.getProperty(key)).orElse("");
        return success(Map.of(key, property));
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void fileDownload(@RequestParam("file") String filePath, HttpServletResponse httpResponse) throws IOException {
        log.info("download file = " + filePath);

        File file = new File(filePath);
        if (!file.exists()) {
            httpResponse.sendError(HttpStatus.NOT_FOUND.value(), "要下载的文件不存在"); // 返回404错误
            return;
        }
        if (file.isDirectory()) {
            httpResponse.sendError(HttpStatus.FORBIDDEN.value(), "不支持下载目录"); // 返回403错误
            return;
        }

        httpResponse.setHeader("Content-Disposition", String.format("attachment;filename=%s", URLEncoder.encode(file.getName(), UTF_8)));
        httpResponse.setContentType("application/octet-stream;charset=utf-8");
        httpResponse.setContentLengthLong(file.length());

        try (FileInputStream fileInputStream = FileUtils.openInputStream(file);
             ServletOutputStream outputStream = httpResponse.getOutputStream()) {
            IOUtils.copy(fileInputStream, outputStream);
        }
    }

    /**
     * 文件上传 MultipartFile
     */
    @PostMapping("/upload")
    public ApiResult<String> fileUpload(@RequestParam("file") MultipartFile file) {
        var filename = file.getOriginalFilename();
        var contentType = Optional.ofNullable(file.getContentType()).orElse("");
        var sizeM = file.getSize() / DATA_MB;
        log.info("上传的文件信息：filename = {}, contentType = {} , size = {} MB", filename, contentType, sizeM);

        return ApiResult.success(null, "上传文件成功 filename = " + filename);
    }

}
